package cn.ctodb.cms.web.rest;

import com.codahale.metrics.annotation.Timed;
import cn.ctodb.cms.service.CmsChannelService;
import cn.ctodb.cms.web.rest.util.HeaderUtil;
import cn.ctodb.cms.service.dto.CmsChannelDTO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing CmsChannel.
 */
@RestController
@RequestMapping("/api")
public class CmsChannelResource {

    private final Logger log = LoggerFactory.getLogger(CmsChannelResource.class);
        
    @Inject
    private CmsChannelService cmsChannelService;

    /**
     * POST  /cms-channels : Create a new cmsChannel.
     *
     * @param cmsChannelDTO the cmsChannelDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new cmsChannelDTO, or with status 400 (Bad Request) if the cmsChannel has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/cms-channels")
    @Timed
    public ResponseEntity<CmsChannelDTO> createCmsChannel(@Valid @RequestBody CmsChannelDTO cmsChannelDTO) throws URISyntaxException {
        log.debug("REST request to save CmsChannel : {}", cmsChannelDTO);
        if (cmsChannelDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("cmsChannel", "idexists", "A new cmsChannel cannot already have an ID")).body(null);
        }
        CmsChannelDTO result = cmsChannelService.save(cmsChannelDTO);
        return ResponseEntity.created(new URI("/api/cms-channels/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("cmsChannel", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /cms-channels : Updates an existing cmsChannel.
     *
     * @param cmsChannelDTO the cmsChannelDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated cmsChannelDTO,
     * or with status 400 (Bad Request) if the cmsChannelDTO is not valid,
     * or with status 500 (Internal Server Error) if the cmsChannelDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/cms-channels")
    @Timed
    public ResponseEntity<CmsChannelDTO> updateCmsChannel(@Valid @RequestBody CmsChannelDTO cmsChannelDTO) throws URISyntaxException {
        log.debug("REST request to update CmsChannel : {}", cmsChannelDTO);
        if (cmsChannelDTO.getId() == null) {
            return createCmsChannel(cmsChannelDTO);
        }
        CmsChannelDTO result = cmsChannelService.save(cmsChannelDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("cmsChannel", cmsChannelDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /cms-channels : get all the cmsChannels.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of cmsChannels in body
     */
    @GetMapping("/cms-channels")
    @Timed
    public List<CmsChannelDTO> getAllCmsChannels() {
        log.debug("REST request to get all CmsChannels");
        return cmsChannelService.findAll();
    }

    /**
     * GET  /cms-channels/:id : get the "id" cmsChannel.
     *
     * @param id the id of the cmsChannelDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the cmsChannelDTO, or with status 404 (Not Found)
     */
    @GetMapping("/cms-channels/{id}")
    @Timed
    public ResponseEntity<CmsChannelDTO> getCmsChannel(@PathVariable Long id) {
        log.debug("REST request to get CmsChannel : {}", id);
        CmsChannelDTO cmsChannelDTO = cmsChannelService.findOne(id);
        return Optional.ofNullable(cmsChannelDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /cms-channels/:id : delete the "id" cmsChannel.
     *
     * @param id the id of the cmsChannelDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/cms-channels/{id}")
    @Timed
    public ResponseEntity<Void> deleteCmsChannel(@PathVariable Long id) {
        log.debug("REST request to delete CmsChannel : {}", id);
        cmsChannelService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("cmsChannel", id.toString())).build();
    }

    /**
     * SEARCH  /_search/cms-channels?query=:query : search for the cmsChannel corresponding
     * to the query.
     *
     * @param query the query of the cmsChannel search 
     * @return the result of the search
     */
    @GetMapping("/_search/cms-channels")
    @Timed
    public List<CmsChannelDTO> searchCmsChannels(@RequestParam String query) {
        log.debug("REST request to search CmsChannels for query {}", query);
        return cmsChannelService.search(query);
    }


}
